const BASE_URL = "http://hs.czlazy.com";

class Request {
    /**
     * Request请求方法
     * @param  {String} url    链接
     * @param  {Objece} params 参数
     * @param  {Boolean} isToken  是否携带token
     * @return {Promise}       包含抓取任务的Promise
     */
    getApi(url, params, isToken, method) {
        if (isToken === undefined) isToken = true;
        if (method === undefined) method = 'GET';
        let token = wx.getStorageSync('logintoken') || '';
        if(isToken=='logintokenlinshi'){
            token = wx.getStorageSync('logintokenlinshi') || '';
        }
        const promise = new Promise((resolve, reject) => {
            //判断是否需要置入token
            if (isToken) params = Object.assign({
                'token': token
            }, params)
            wx.request({
                url: `${BASE_URL}${url}`,
                method: method,
                data: params, //置入token
                header: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                success: res => {
                    if (res.statusCode == 200) {
                        if (res.data.code == 1) {
                            resolve(res);
                        } else {
                            if (res.data.code == 103 || res.data.code == 101 || res.data.code == 104) {
                                //token失效
                                reject();
                            } else {
                                wx.showToast({
                                    title: res.data.msg,
                                    icon: 'none',
                                    duration: 1200,
                                    mask: true
                                });
                                reject();
                            }
                        }
                    } else {
                        wx.showToast({
                            title: '[' + res.code + '] 服务器出错,请重试',
                            icon: 'none',
                            duration: 1200
                        });
                        reject(res);
                    }

                },
                fail: err => {
                    console.log(err)
                    wx.showToast({
                        title: '网络错误',
                        icon: 'none',
                        duration: 1200
                    });
                    reject(err);
                },
                complete: () => {
                    
                }
            });
        });

        return promise
    }

}

let request = new Request();

module.exports = {
    get: request.getApi,
    url: BASE_URL
}